package ldh.im.fxgui.controller;

import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;
import ldh.im.fxbase.data.pojo.ImModule;
import ldh.im.fxbase.data.pojo.ImModuleItem;
import ldh.im.fxbase.data.pojo.status.ImModuleItemStatus;
import ldh.im.fxbase.data.pojo.status.ImModuleItemType;
import ldh.im.fxbase.data.pojo.status.ImModuleStatus;
import ldh.im.fxbase.service.ModuleService;
import ldh.im.fxbase.util.*;
import ldh.im.fxgui.component.SearchTextField;
import ldh.im.fxgui.component.WebViewPage;
import ldh.im.fxgui.component.cell.ModuleItemView;
import ldh.im.fxgui.util.UiUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URL;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;
import java.util.ResourceBundle;

public class WorkbenchController implements Initializable {

    private static final Logger LOGGER = LoggerFactory.getLogger(WorkbenchController.class);

    @FXML private StageControlController stagePaneController;
    @FXML private Pane movablePane;
    @FXML private SearchTextField searchTextField;
    @FXML private VBox root;

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        MovableHelper.movable(movablePane);

        ThreadPoolUtil.submit(()->{
            try {
                ModuleService moduleService = new ModuleService();
                List<ImModule> modules = moduleService.getModules();

                String userId = UiUtil.getLoginImUser().getUserId();
                ImModule historyModule = moduleService.getHistoryModule(userId);

                FxThreadUtil.runLater(()->{
                    if (historyModule != null) {
                        historyModule.setName("历史查看记录");
                        buildModuleUi(historyModule);
                    }
                    for (ImModule module : modules) {
                        buildModuleUi(module);
                    }
                });
            } catch (Exception e) {
                LOGGER.error("load module data failure", e);
            }

        });
    }

    private void buildModuleUi(ImModule imModule) {
        if (imModule.getModuleItemList() == null || imModule.getModuleItemList().size() < 1) return;
        Label title = new Label(imModule.getName());
        title.getStyleClass().add("group-title");

        FlowPane flowPane = new FlowPane(10, 10);
        for (ImModuleItem imModuleItem : imModule.getModuleItemList()) {
            ModuleItemView moduleItemView = new ModuleItemView(imModuleItem);
            bindEvent(moduleItemView, imModule, imModuleItem);
            flowPane.getChildren().add(moduleItemView);
        }
        root.getChildren().addAll(title, flowPane);
    }

    private void bindEvent(ModuleItemView moduleItemView, ImModule imModule, ImModuleItem imModuleItem) {
        moduleItemView.setOnMouseClicked(e-> {
            ThreadPoolUtil.submit(()->{
                try {
                    if (imModule.getName().equals("历史查看记录")) {
                        ModuleService moduleService = new ModuleService();
                        moduleService.update(imModule);
                    } else {
                        saveOrUpdateHistoryModule(imModuleItem);
                    }
                    if (imModuleItem.getType() == ImModuleItemType.page) {
                        FxThreadUtil.runLater(()->{
                            WebViewPage webViewPage = new WebViewPage(imModuleItem.getUrl());
                            webViewPage.show();
                        });
                    } else {
                        // 原生启动
                    }
                } catch (Exception ee) {
                    LOGGER.error("show module item failure", ee);
                }
            });
        });
    }

    private void saveOrUpdateHistoryModule(ImModuleItem imModuleItem) throws SQLException {
        String userId = UiUtil.getLoginImUser().getUserId();

        ImModule newHistoryModule = new ImModule();
        newHistoryModule.setName(userId + "_history");
        newHistoryModule.setNo(1000);
        newHistoryModule.setStatus(ImModuleStatus.enable);

        ImModuleItem moduleItem = new ImModuleItem();
        moduleItem.setName(imModuleItem.getModuleId() + "_" +  imModuleItem.getName());
        moduleItem.setNo(1000);
        moduleItem.setType(imModuleItem.getType());
        moduleItem.setIcon("");
        moduleItem.setStatus(ImModuleItemStatus.enable);
        newHistoryModule.setModuleItemList(Arrays.asList(moduleItem));


        ModuleService moduleService = new ModuleService();
        moduleService.saveOrUpdate(newHistoryModule);
    }
}
